package com.ck.lock.deadlock;


/**
 * @author ck
 * @date 2023/7/4 15:54
 */
public class DeadLockDemoTest {

    private static Object lock1 = new Object();
    private static Object lock2 = new Object();


    public static void main(String[] args) {

        /**
         * 死锁问题
         */
        Thread thread1 = new Thread(()->{
            synchronized (lock1){
                System.out.println(Thread.currentThread().getName()+"获取到了lock1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2){
                    System.out.println(Thread.currentThread().getName()+"获取到了lock2");
                }
            }
        },"线程1");

        Thread thread2 = new Thread(()->{
            synchronized (lock2){
                System.out.println(Thread.currentThread().getName()+"获取到了lock2");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1){
                    System.out.println(Thread.currentThread().getName()+"获取到了lock1");
                }
            }
        },"线程2");

        thread1.start();
        thread2.start();



        /**
         * 1、解决方法
         * 避免循环依赖：设计锁的获取顺序，确保所有线程按照相同的顺序获取锁。这样可以避免不同线程之间的循环依赖，减少死锁的可能性
         *
         *  Thread thread1 = new Thread(()->{
         *             synchronized (lock1){
         *                 System.out.println(Thread.currentThread().getName()+"获取到了lock1");
         *                 try {
         *                     Thread.sleep(1000);
         *                 } catch (InterruptedException e) {
         *                     e.printStackTrace();
         *                 }
         *                 synchronized (lock2){
         *                     System.out.println(Thread.currentThread().getName()+"获取到了lock2");
         *                 }
         *             }
         *         },"线程1");
         *
         *         Thread thread2 = new Thread(()->{
         *             synchronized (lock1){
         *                 System.out.println(Thread.currentThread().getName()+"获取到了lock1");
         *                 try {
         *                     Thread.sleep(1000);
         *                 } catch (InterruptedException e) {
         *                     e.printStackTrace();
         *                 }
         *                 synchronized (lock2){
         *                     System.out.println(Thread.currentThread().getName()+"获取到了lock2");
         *                 }
         *             }
         *         },"线程2");
         *
         *         thread1.start();
         *         thread2.start();
         *
         *     }
         */
    }


}

